package connectionpool;

import java.sql.Connection;
import java.util.Vector;

/**
 * Created by Administrator on 2018/2/23 0023.
 */
public class ConnectionPool {
    Vector<PoolConnection> connections = new Vector<PoolConnection>();

    private ConnectionPool() {
        initPool();
    }

    private static ConnectionPool pool = new ConnectionPool();

    public static ConnectionPool getPool() {
        return pool;
    }

    public void initPool() {
        while (connections.size() < 10) {
            Connection connection = DBUtil.getConnection();
            connections.add(new PoolConnection(connection));
        }
        System.out.println("连接池初始化完毕！");
    }

    public synchronized Connection getConnection() {
        Connection connection = getFreeConnection();
        while (connection == null) {
            try {
                wait(200);
                System.out.println("等待连接池创建连接！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            connection = getFreeConnection();
        }
        return connection;
    }

    public Connection getFreeConnection() {
        Connection connection = null;
        for (PoolConnection poolConnection : connections) {
            if (!poolConnection.isUse()) {
                connection = poolConnection.getConnection();
                poolConnection.setUse(true);
                break;
            }
        }
        return connection;
    }

    public synchronized  void returnConnection(Connection connection) {
        for (PoolConnection poolConnection : connections) {
            if (poolConnection.getConnection() == connection) {
                poolConnection.setUse(false);
                break;
            }
        }
    }

    public synchronized int getConnectionCount() {
        int i = 0;
        for (PoolConnection poolConnection : connections) {
            if (!poolConnection.isUse()) {
                i++;
            }
        }
        return i;
    }

}
